package com.stock.calculator.helper;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.stock.calculator.utils.URLHttpConnect;

public class StockQuoteHelper {

    private static final String YQL_URL    = "http://query.yahooapis.com/v1/public/yql";
    private static final String YQL_QUERY  = "q="
                                                   + URLEncoder
                                                           .encode("select * from yahoo.finance.quotes where symbol=\"_tickerSymbol_\"");
    private static final String YQL_ENV    = "env=" + URLEncoder.encode("http://datatables.org/alltables.env");
    private static final String YQL_FORMAT = "format=json";

    private final String        URL;
    private JsonParser          parser     = new JsonParser();

    public StockQuoteHelper(String tickerSymbol) {
        String query = YQL_QUERY.replaceAll("_tickerSymbol_", tickerSymbol) + "&" + YQL_ENV + "&" + YQL_FORMAT;

        URL = YQL_URL + "?" + query;
    }

    public Map<String, String> fetchQuote() throws IOException {
        String response = URLHttpConnect.httpGet(URL);
        
        JsonElement jsonElementResponse = parser.parse(response);
        JsonObject quoteJsonObject = jsonElementResponse.getAsJsonObject().get("query").getAsJsonObject()
                .get("results").getAsJsonObject().get("quote").getAsJsonObject();

        Map<String, String> quote = new HashMap<String, String>();

        for (Entry<String, JsonElement> entry : quoteJsonObject.entrySet()) {

            String key = entry.getKey();
            JsonElement valueJsonElement = entry.getValue();

            String value = valueJsonElement.isJsonNull() ? null : valueJsonElement.toString().replaceAll("((&.{1,5};)|(<.{1,3}>)|\")", "");
            quote.put(key, value);
        }
        return quote;
    }
    
    public static void main(String s[]) throws IOException{
        Map<String, String> quote = new StockQuoteHelper("ORCL").fetchQuote();
        
        for(String key : quote.keySet()){
            System.out.format("%53s %20s\n", key, quote.get(key));
        }
    }
    
}